package com.peanut.baby.mvp.liveroom;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.R;
import com.peanut.baby.model.LiveMsg;
import com.peanut.baby.model.LiveMsgContent;
import com.peanut.baby.model.LiveRoom;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.devlibrary.RequestResult;
import com.peanut.devlibrary.adapter.FragmentTabAdapter;
import com.peanut.devlibrary.camera.CameraActivity;
import com.peanut.devlibrary.picker.ImageCaptureManager;
import com.peanut.devlibrary.picker.ImageConfig;
import com.peanut.devlibrary.picker.PhotoPickerActivity;
import com.peanut.devlibrary.widget.TitleBackTextView;
import com.tencent.mars.xlog.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/7/17.
 */

public class LiveRoomActivity extends BaseMvpActivity implements RadioGroup.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener, LiveRoomContract.View, View.OnClickListener{
    private static final String TAG = LiveRoomActivity.class.getSimpleName();

    @BindView(R.id.room_radio_group)
    RadioGroup roomRadioGroup;
    @BindView(R.id.room_viewpager)
    ViewPager roomViewpager;

    ArrayList<Fragment> fragments;
    FragmentTabAdapter adapter;
    RoomLectureFragment lectureFragment;
    RoomDiscussFragment discussFragment;
    @BindView(R.id.room_back)
    TitleBackTextView roomBack;

    private LiveRoomPresenter presenter;

    private Timer loopTimer;
    private TimerTask loopTask;

    private LiveRoom room;

    private List<LiveMsg> messages;
    int lastMessageId = 0;

    private boolean isRequesting = false;

    public static void start(Context ctx, LiveRoom liveRoom) {
        ctx.startActivity(new Intent(ctx, LiveRoomActivity.class).putExtra("liveRoom", liveRoom));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_room);
        ButterKnife.bind(this);
        room = (LiveRoom) getIntent().getSerializableExtra("liveRoom");
        if (room == null) {
            showToast("直播间异常");
            finish();
        }
        initView();

        presenter = new LiveRoomPresenter(this,this);
        startLoopTimer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (AppVoicePlayer.getInstance().isPlaying()) {
            Log.d(RoomLectureFragment.class.getSimpleName(),"room on Pause");
            AppVoicePlayer.getInstance().releasePlayer();
        }
    }

    public int getRoomId() {
        return room.roomId;
    }

    /**
     *
     */
    private void startLoopTimer() {
        Log.d(TAG, "startLoopTimer");
        loopTask = new LoopTimerTask();
        loopTimer = new Timer();
        loopTimer.schedule(loopTask, 0, 2000);
    }


    private void stopLoopTimer() {
        Log.d(TAG, "stopLoopTimer");
        if (loopTimer != null) {
            loopTimer.cancel();
        }
        loopTimer = null;
        if (loopTask != null) {
            loopTask.cancel();
        }
        loopTask = null;
    }


    @Override
    protected void onDestroy() {
        stopLoopTimer();
        AppVoicePlayer.getInstance().onDestory();
        super.onDestroy();

    }

    private void initView() {
        roomBack.setOnClickListener(this);
        roomViewpager.setOnPageChangeListener(this);
        roomRadioGroup.setOnCheckedChangeListener(this);

        fragments = new ArrayList<>();
        lectureFragment = RoomLectureFragment.newInstance(room);
        discussFragment = RoomDiscussFragment.newInstance(room);
        fragments.add(lectureFragment);
        fragments.add(discussFragment);
        adapter = new FragmentTabAdapter(getSupportFragmentManager(), fragments);
        roomViewpager.setAdapter(adapter);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setCurrent(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void setCurrent(int currentIndex) {
        hideSoftKeyboard();
        RadioButton radioButton = (RadioButton) roomRadioGroup.getChildAt(currentIndex);
        if (!radioButton.isChecked()) {
            radioButton.setChecked(true);
        }

        if (roomViewpager.getCurrentItem() != currentIndex) {
            roomViewpager.setCurrentItem(currentIndex);
        }

    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.room_lecture:
                setCurrent(0);
                break;
            case R.id.room_discuss:
                setCurrent(1);
                break;
        }
    }

    @Override
    public void onMessageListGet(List<LiveMsg> _messages) {
        if (messages == null) {
            messages = new ArrayList<>();
        }
        if (_messages != null && !_messages.isEmpty()) {
            messages.addAll(_messages);
        }
        spiltMessageBlock(_messages);
        isRequesting = false;
    }

    /**
     * @param _messages
     */
    private void spiltMessageBlock(List<LiveMsg> _messages) {
        if (_messages == null || _messages.isEmpty()) {
            return;
        }
        List<LiveMsg> lectureMessages = new ArrayList<>();
        List<LiveMsg> discussMessages = new ArrayList<>();
        for (int i = 0; i < _messages.size(); i++) {
            LiveMsg msg = _messages.get(i);
            Log.d(TAG, "spiltMessageBlock: " + msg.tabType);
            if (msg.tabType == LiveMsg.TAB_LECTURE) {
                lectureMessages.add(msg);
            } else if (msg.tabType == LiveMsg.TAB_DISCUSS) {
                discussMessages.add(msg);
            }
        }
        if(lastMessageId == 0){
            lectureMessages.add(0,getWelcomMessage());
        }

        if (!lectureMessages.isEmpty()) {
            lectureFragment.onMessageGet(lectureMessages);
        }

        if (!discussMessages.isEmpty()) {
            discussFragment.onMessageGet(discussMessages);
        }

    }

    @Override
    public void onRequestFailed(String failReason) {
        dismissProgressDialog();
        showToast(failReason);
        isRequesting = false;
    }

    @Override
    public void onSendMessageSuccess(LiveMsg message) {
        if (roomViewpager.getCurrentItem() == 0) {
            lectureFragment.onSendMessageSuccess();
        } else {
            discussFragment.onSendMessageSuccess();
        }
        dismissProgressDialog();
        requestMessageList();
    }

    @Override
    public void onPicturePermissionGranted() {
        PhotoPickerActivity.startForResult(LiveRoomActivity.this, 1, false, PhotoPickerActivity.MODE_SINGLE, new ImageConfig());
    }

    @Override
    public void onPicturePermissionDenied() {
        showToast("您需要在权限设置中打开权限才能发送图片");
    }

    @Override
    public void onAudioPermissionGranted() {

    }

    @Override
    public void onAudioPermissionDenied() {
        showToast("您需要在权限设置中打开权限才能拍照");
    }

    @Override
    public void onCameraPermissionGranted() {
        CameraActivity.startForResult(LiveRoomActivity.this);
    }

    @Override
    public void onCameraPermissionDenied() {
        showToast("您需要在权限设置中打开权限才能录音");
    }

    @Override
    public void onUploadPictureFinished(boolean success, String resultOrReason, UploadConf config) {
        dismissProgressDialog();
        if (success) {
            if (roomViewpager.getCurrentItem() == 0) {
                lectureFragment.onPictureUploadSuccess(config);
            } else {
                discussFragment.onPictureUploadSuccess(config);
            }
        } else {
            showToast(resultOrReason);
        }
    }

    public void checkCameraPermission() {
        presenter.checkCameraPermission(this);
    }

    public void checkPicturePermission() {
        presenter.checkPicturePermission(this);
    }

    public void checkVoicePermission() {
        presenter.checkAudioPermission(this);
    }

    public void uploadAudio(String path, long duration) {
        showProgressDialog("正在发送...", false);
        presenter.uploadAudio(path, duration);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RequestResult.REQUEST_CODE_CAMERA:
                ImageCaptureManager captureManager = new ImageCaptureManager(LiveRoomActivity.this);
                String path = data.getStringExtra("result");
                captureManager.galleryAddPic(path);
                onResultPhotoGet(path);
                break;
            case RequestResult.REQUEST_CODE_PHOTOS:
                List<String> resultList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                Log.d(TAG, "resultList: " + (resultList == null ? "null" : "result list: " + resultList.size()));
                if (resultList != null && !resultList.isEmpty()) {
                    onResultPhotoGet(resultList.get(0));
                }
                break;
        }
    }

    private void onResultPhotoGet(String path) {
        Log.d(TAG, "onResultPhotoGet: " + path);
        showProgressDialog("正在发送...", false);
        presenter.compressAndUploadPhoto(path);
    }

    @Override
    public void sendMessage(LiveMsg msg) {
        showProgressDialog("正在发送...", false);
        presenter.sendMessage(msg, getRoomId() + "");
    }

    @Override
    public void onUploadAudioFinished(boolean success, String failReason, UploadConf config) {
        dismissProgressDialog();
        if (success) {
            lectureFragment.onAudioUploadSuccess(config);
        } else {
            showToast(failReason);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.room_back:
                finish();
                break;
        }
    }

    class LoopTimerTask extends TimerTask {

        @Override
        public void run() {
            requestMessageList();
        }
    }

    /**
     *
     */
    private synchronized void requestMessageList() {
        if(isRequesting){
            Log.i(TAG,"requestMessageList is in request "+isRequesting);
            return;
        }
        isRequesting = true;
        presenter.getMessageList(getLastMessageId() + "", getRoomId() + "");
    }

    private int getLastMessageId() {
        if (messages == null || messages.isEmpty()) {
            lastMessageId = 0;
            return 0;
        }
        lastMessageId = messages.get(messages.size() - 1).id;
        return lastMessageId;
    }

    private LiveMsg getWelcomMessage(){
        LiveMsg message = new LiveMsg();
        message.tabType = LiveMsg.TAB_LECTURE;
        message.messageType = LiveMsg.TYPE_TEXT;
        message.roomId = getRoomId();
        message.createTime = System.currentTimeMillis();
        LiveMsgContent content = new LiveMsgContent(textToJsonString(room.welcome));
        message.message = content;
        message.nickname = room.serverName;
        return message;

    }

    private String textToJsonString(String text){
        JSONObject obj = new JSONObject();
        try {
            obj.put("text",text);
        } catch (JSONException e) {
            obj = null;
            return "";
        }
        return obj.toString();
    }
}
